package com.it.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.it.aiDispatch.DispatchApi;
import com.it.aiReportClaim.ReportClaimApi;
import com.it.entity.dispatch.AiClaimDispatch;
import com.it.entity.survey.AiSurveyReport;
import com.it.mapper.AiSurveyReportMapper;
import com.it.pojo.PageResult;
import com.it.service.AiSurveyReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.vo.AiSurveyReportVo;
import com.it.vo.ReportVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import utils.R;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yzy
 * @since 2025年09月20日
 */
@Service
public class AiSurveyReportServiceImpl extends ServiceImpl<AiSurveyReportMapper, AiSurveyReport> implements AiSurveyReportService {

    @Autowired
    private AiSurveyReportMapper aiSurveyReportMapper;

    @Autowired
    private DispatchApi dispatchApi;

    @Autowired
    private ReportClaimApi reportClaimApi;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private ThumbImageConfig thumbImageConfig;
    @Value("${fdfs.view-base-url:}")
    private String basePath;

    @Override
    public R getAiSurveyReport(String reportNo) {

        LambdaQueryWrapper<AiSurveyReport> queryWrapper = new LambdaQueryWrapper<AiSurveyReport>();
        queryWrapper.eq(AiSurveyReport::getReportNo,reportNo);
        queryWrapper.eq(AiSurveyReport::getSurveyStatus,3);

        //AiSurveyReport aiSurveyReport = aiSurveyReportMapper.selectOne(queryWrapper);
        // 返回对应报案号的所有查勘信息
        List<AiSurveyReport> aiSurveyReportList = aiSurveyReportMapper.selectList(queryWrapper);

        if(aiSurveyReportList != null){
            return R.Success("该案件已查勘过",aiSurveyReportList);
        }
        return R.Failed("查勘未结束");
    }

    @Override
    public R select(ReportVo reportVo, Integer pageNum, Integer pageSize) {
        if (reportVo == null) {
            throw new IllegalArgumentException("查询参数不能为空");
        }
        // 1. 校验分页参数
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1; // 默认第一页
        }
        if (pageSize == null || pageSize <= 0 || pageSize > 100) {
            pageSize = 10; // 限制最大每页条数，默认10条
        }

        // 2. 调用Mapper层获取全部数据（不分页）
        List<ReportVo> allData = aiSurveyReportMapper.select(reportVo);

        // 3. 计算总记录数
        int total = allData.size();

        // 4. 计算分页起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        // 处理超出总条数的情况
        if (startIndex >= total) {
            // 如果起始索引超过总条数，返回空列表
            return R.Success(buildPageResult(pageNum, pageSize, total, new ArrayList<>()));
        }

        int endIndex = Math.min(startIndex + pageSize, total);

        // 5. 截取当前页数据
        List<ReportVo> currentPageData = allData.subList(startIndex, endIndex);

        // 6. 构建分页结果并返回
        return R.Success(buildPageResult(pageNum, pageSize, total, currentPageData));
    }

    @Override
    public R selectDispatchList(Integer pageNum, Integer pageSize,String reportId) {

        // 1. 校验分页参数
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1; // 默认第一页
        }
        if (pageSize == null || pageSize <= 0 || pageSize > 100) {
            pageSize = 10; // 限制最大每页条数，默认10条
        }

        // 2. 调用Mapper层获取全部数据（不分页）
        List<AiClaimDispatch> allData = aiSurveyReportMapper.selectDispatchList(reportId);

        // 3. 计算总记录数
        int total = allData.size();

        // 4. 计算分页起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        // 处理超出总条数的情况
        if (startIndex >= total) {
            // 如果起始索引超过总条数，返回空列表
            return R.Success(buildPageResultB(pageNum, pageSize, total, new ArrayList<>()));
        }

        int endIndex = Math.min(startIndex + pageSize, total);

        // 5. 截取当前页数据
        List<AiClaimDispatch> currentPageData = allData.subList(startIndex, endIndex);

        // 6. 构建分页结果并返回
        return R.Success(buildPageResultB(pageNum, pageSize, total, currentPageData));
    }

    @Override
    public void updateStatus(int dispatchId) {
        LocalDateTime localDateTime = LocalDateTime.now();
        aiSurveyReportMapper.updateStatus(dispatchId,localDateTime);

    }

    @Override
    public void rejectedDispatch(int dispatchId,String cancelReason) {
        LocalDateTime localDateTime = LocalDateTime.now();
        aiSurveyReportMapper.rejectedDispatch(dispatchId,localDateTime,cancelReason);
    }

    @Override
    public void addSurvey(String surveyInWorkNo, String reportNo) {
        aiSurveyReportMapper.addSurvey(surveyInWorkNo,reportNo);

    }

    @Override
    public R getDispatch(Integer pageNum,Integer pageSize,String reportId) {
        // 1. 校验分页参数
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1; // 默认第一页
        }
        if (pageSize == null || pageSize <= 0 || pageSize > 100) {
            pageSize = 10; // 限制最大每页条数，默认10条
        }

        // 2. 调用Mapper层获取全部数据（不分页）
        List<AiSurveyReportVo> allData=aiSurveyReportMapper.selectDispatch(reportId);

        // 3. 计算总记录数
        int total = allData.size();

        // 4. 计算分页起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        // 处理超出总条数的情况
        if (startIndex >= total) {
            // 如果起始索引超过总条数，返回空列表
            return R.Success(buildPageResultC(pageNum, pageSize, total, new ArrayList<>()));
        }

        int endIndex = Math.min(startIndex + pageSize, total);

        // 5. 截取当前页数据
        List<AiSurveyReportVo> currentPageData = allData.subList(startIndex, endIndex);

        // 6. 构建分页结果并返回
        return R.Success(buildPageResultC(pageNum, pageSize, total, currentPageData));
    }

    @Override
    public R singleImage(MultipartFile file) {
        try {
            //读取文件大小
            long size = file.getSize();
            //后缀
            String originalFilename = file.getOriginalFilename();
            int lastIndex = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(lastIndex+1);
            //输入流
            InputStream is = null;
            is = file.getInputStream();
            StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(is,size,extName,null);
            String fullPath = storePath.getFullPath();
            System.out.println("上传路径:" + fullPath);
            System.out.println("上传路径缩略图:" + thumbImageConfig.getThumbImagePath(fullPath));
            return R.Success("图片上传成功",basePath + "/" + fullPath);
        } catch (IOException e) {
            e.printStackTrace();
            return R.Failed("图片上传失败");
        }
    }

    @Override
    public R deleteImage(String url) {
        try {
            fastFileStorageClient.deleteFile(url);
            return R.Success("图片清理成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return R.Failed("图片清理失败");
        }
    }

    @Override
    public void updateStatusB(String reportId) {

        aiSurveyReportMapper.updateStatusB(reportId);

    }

    @Transactional
    @Override
    public void updateByReportNo(AiSurveyReport aiSurveyReport) {

        // 1. 更新查勘报告
        aiSurveyReportMapper.updateByReportNo(aiSurveyReport);

        // 2. 更新当前调度记录状态
        dispatchApi.updateStatus(aiSurveyReport.getReportNo(), aiSurveyReport.getSurveyInWorkNo(), 4);

        // 3. 检查该报案号的所有调度记录是否都已完成
        boolean allDispatchesCompleted = checkAllDispatchesCompleted(aiSurveyReport.getReportNo());

        // 4. 只有当所有调度都完成时，才更新报案表状态
        if (allDispatchesCompleted) {
            reportClaimApi.updateStatus(aiSurveyReport.getReportNo(), 3);
        }

    }

    @Override
    public R selectDispatch(Integer pageNum, Integer pageSize, String reportId, String surveyInWorkNo) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<AiSurveyReport> queryWrapper = new LambdaQueryWrapper<AiSurveyReport>();
        if (!StringUtils.isBlank(reportId)) {
            queryWrapper.eq(AiSurveyReport::getReportNo,reportId);
        }
        if (!StringUtils.isBlank(surveyInWorkNo)) {
            queryWrapper.eq(AiSurveyReport::getSurveyInWorkNo,surveyInWorkNo);
        }
        queryWrapper.eq(AiSurveyReport::getSurveyStatus,3);
        List<AiSurveyReport> list = aiSurveyReportMapper.selectList(queryWrapper);
        PageInfo<AiSurveyReport> pageInfo = new PageInfo<>(list);
        return R.Success("查询成功",pageInfo);
    }


    /**
     * 检查该报案号的所有调度记录是否都已完成（状态为4）
     */
    private boolean checkAllDispatchesCompleted(String reportNo) {
        // 查询该报案号的所有调度记录
        List<AiClaimDispatch> dispatchList = dispatchApi.selectByReportNo(reportNo);

        if (dispatchList == null || dispatchList.isEmpty()) {
            return false;
        }
        // 检查是否所有调度记录的状态都是4（查勘完成）
        return dispatchList.stream()
                .allMatch(dispatch -> dispatch.getDispatchStatus() == 4);
    }

    /**
     * 构建分页结果对象
     */
    private PageResult<ReportVo> buildPageResult(Integer pageNum, Integer pageSize, int total, List<ReportVo> data) {
        PageResult<ReportVo> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);          // 当前页码
        pageResult.setPageSize(pageSize);        // 每页条数
        pageResult.setTotal(total);              // 总记录数
        pageResult.setTotalPages((total + pageSize - 1) / pageSize); // 总页数
        pageResult.setData(data);                // 当前页数据
        return pageResult;
    }

    private PageResult<AiClaimDispatch> buildPageResultB(Integer pageNum, Integer pageSize, int total, List<AiClaimDispatch> data) {
        PageResult<AiClaimDispatch> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);          // 当前页码
        pageResult.setPageSize(pageSize);        // 每页条数
        pageResult.setTotal(total);              // 总记录数
        pageResult.setTotalPages((total + pageSize - 1) / pageSize); // 总页数
        pageResult.setData(data);                // 当前页数据
        return pageResult;
    }

    private PageResult<AiSurveyReportVo> buildPageResultC(Integer pageNum, Integer pageSize, int total, List<AiSurveyReportVo> data) {
        PageResult<AiSurveyReportVo> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);          // 当前页码
        pageResult.setPageSize(pageSize);        // 每页条数
        pageResult.setTotal(total);              // 总记录数
        pageResult.setTotalPages((total + pageSize - 1) / pageSize); // 总页数
        pageResult.setData(data);                // 当前页数据
        return pageResult;
    }
}
